package com.yan.gulimall.auth.Controller;

import com.alibaba.fastjson.TypeReference;
import com.yan.common.constant.AuthServerConstant;
import com.yan.common.exception.BizCodeEnume;
import com.yan.common.utils.R;
import com.yan.common.vo.MemberResponseVo;
import com.yan.gulimall.auth.feign.MemberFeignService;
import com.yan.gulimall.auth.feign.ThirdPartyFeignService;
import com.yan.gulimall.auth.vo.UserLoginVo;
import com.yan.gulimall.auth.vo.UserRegisterVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    ThirdPartyFeignService thirdPartyFeignService;

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 登录注册功能
     * @return
     */
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone){

        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        long time = Long.parseLong(redisCode.split("_")[1]);
        if (System.currentTimeMillis() - time < 60000){
            // 60 s 不能重复发送
            return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(),BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
        }

        // sms:code:phone -> 123456
        String code = UUID.randomUUID().toString().substring(0, 5);
        String substring = code+"_"+System.currentTimeMillis();
        // redis中sendCode的值保存10分钟
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,substring,10, TimeUnit.MINUTES);
        thirdPartyFeignService.sendCode(phone,substring);
        return R.ok();
    }

    /**
     * TODO 需要解决分布式session问题
     * @param userRegisterVo
     * @param result
     * @param redirectAttributes
     * @return
     */

    @PostMapping("register")
    public  String register(@Valid UserRegisterVo userRegisterVo, BindingResult result, RedirectAttributes redirectAttributes){

        if (result.hasErrors()){
//            result.getFieldErrors().stream().map(fieldError -> {
//                String field = fieldError.getField();
//                String defaultMessage = fieldError.getDefaultMessage();
//                errors.put(field,defaultMessage);
//                return
//            });
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,FieldError::getDefaultMessage));

            //model.addAttribute("errors",errors);
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/register.html";
        }

        // 调用远程注册
        String code = userRegisterVo.getCode();
        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegisterVo.getPhone());
        if(!StringUtils.isEmpty(s)){
            // 验证码验证成功
            if(code.equals(s.split("_")[0])){
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegisterVo.getPhone());
                R r = memberFeignService.reg(userRegisterVo);
                if (r.getCode()==0){
                    // 成功
                    return "redirect:http://auth.gulimall.com/login.html";
                } else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", r.getData(new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.gulimall.com/register.html";
                }

            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code","验证码错误或过期,请重试");
                //model.addAttribute("errors",errors);
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.gulimall.com/register.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误或过期,请重试");
            //model.addAttribute("errors",errors);
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/register.html";
        }
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object user = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (user==null){
            return "login";
        } else {
            return "redirect:http://gulimall.com";
        }

    }


    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo, RedirectAttributes redirectAttributes, HttpSession session){

        // 远程登录
        R login = memberFeignService.login(userLoginVo);
        if (login.getCode()==0){
            // 登录成功
            MemberResponseVo data = login.getData("data", new TypeReference<MemberResponseVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);
            return "redirect:http://gulimall.com";
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://gulimall.com/login.html";
        }
    }
}
